package com.pan.common.util;

import com.pan.seed.Node;

import java.util.ArrayList;
import java.util.List;

/**
 * @author by panstark
 * @description
 * @notice
 * @date 2020/12/31
 */
public class NodeUtil {


    public static Node getLengthNodeInteger(int length){

        Node start = new Node(0);
        addNext(start,0,length);
        return start;
    }


    /**
     * 获取一个带圆环的Node
     * @param length
     * @return
     */
    public static Node getCircleNode(int length){

        Node start = new Node(0);
        addNext(start,0,length);
        Node node = getLastNode(start);
        Node random = getRandomNode(start);
        node.setNext(random);
        return start;
    }

    public static boolean isCircleNode(Node node){

        Node slowNode = node;
        int i=0;
        while(node!=null){
            Node next = node.getNext();
            i++;
            if(i%2==0){
                i=0;
                 slowNode = slowNode.getNext();
                 if(slowNode==next){
                     return true;
                 }
            }
            node = next;
        }
        return false;
    }


    private static Node getRandomNode(Node start) {

        List<Node> list = new ArrayList<>();
        list.add(start);
        while(start.getNext()!=null){
            Node next = start.getNext();
            list.add(next);
            start = next;
        }
        int index = (int)(Math.random()*list.size());
        return list.get(index);
    }

    /**
     * 取到链表的最后一个
     * @param start
     * @return
     */
    private static Node getLastNode(Node start) {

        while(start.getNext()!=null){

           start = start.getNext();
       }

         return start;
    }

    /**
     * 添加下一个节点
     * @param start
     * @param i
     * @param length
     */
    private static void addNext(Node start, int i,int length) {
        i++;
        if(i==length){
            return;
        }
        Node next = new Node(i);
        start.setNext(next);
        addNext(next,i,length);
    }

    public static void lookAllNode(Node node){

        do{
            Object t = node.getT();
            System.out.println("node装在的数据："+t);
            node = node.getNext();
        }while(node!=null);
    }

    public static Node reverNode(Node node){

        //翻转后的链表
        Node revertNode = null;
        //当前头结点
        Node head = node;

        while(head!=null){
            Node tail = head.getNext();
            head.setNext(revertNode);
            revertNode=head;
            head=tail;
        }

        return revertNode;
    }

    public static void main(String[] args) {

        Node circleNode = getCircleNode(10);
        Node lengthNodeInteger = getLengthNodeInteger(10);
        System.out.println(isCircleNode(circleNode));
        //Node node = reverNode(lengthNodeInteger);
        //lookAllNode(lengthNodeInteger);

    }
}
